<?php

namespace app\cms\controller;

use app\cms\model\CmsWareInbound;
use app\cms\model\cmsWareInboundDetail;
use app\cms\model\cmsWareInboundFinance;
use app\cms\model\CmsWareInfo;
use app\cms\service\InboundService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemBase;
use think\admin\service\AdminService;

/**
 * 入库管理
 * Class Portal
 * @package app\cms\controller\Inbound
 */
class Inbound extends Controller
{
  /**
   * 入库管理
   * @auth true
   * @menu true
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function index2()
  {
    $this->title = '入库管理';
    $query = CmsWareInbound::mQuery();
    $query->order('created_at desc')->page();
  }

  /**
   * 编辑仓库
   * @auth true
   * @menu true
   */
  public function index()
  {
    CmsWareInbound::mQuery()->layTable(function () {
      $this->title = '入库管理';
      $this->warehouses = InboundService::instance()->getWarehouses();
    }, function (QueryHelper $query) {
      $query->like('account,user_name,mobile')->equal('depart_code,receiver_code')->order('created_at desc')->dateBetween('created_at');
    });
  }

  protected function _index_page_filter(array &$data)
  {

    $house = CmsWareInfo::mk()->where(['deleted' => 0])->column('ware_name', 'ware_code');

    foreach ($data as &$vo) {
      $vo['receiver_name'] = $house[$vo['receiver_code']] ?? '';
      $vo['depart_name'] = $house[$vo['depart_code']] ?? '';
    }
  }

  /**
   * 添加入库单
   * @auth true
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function add()
  {
    CmsWareInbound::mForm('add', 'id');
  }

  protected function _add_form_filter(array &$data)
  {
    if ($this->request->isPost()) {


      $bill_no = InboundService::instance()->generatorCode();
      
      $data['bill_no'] = $bill_no;
      $user_name = AdminService::instance()->getUserName();
      $data['user_name'] = $user_name;
      $data['user_id'] = AdminService::instance()->getUserId();


      $detail_arr = json_decode($data['details'],true);
    
      $details = [];
      $total_weight = 0;
      $total_num = 0;
      $total_price = 0;
      foreach ($detail_arr as $k => $value) {

        $weight = floatval($detail_arr[$k]['weight']) ?? 0;
        $other_weight = floatval($detail_arr[$k]['other_weight']) ?? 0;
        $gross_weight = floatval($detail_arr[$k]['gross_weight']) ?? 0;
        $unit_price = floatval($detail_arr[$k]['unit_price']) ?? 0;
        $price = floatval($detail_arr[$k]['price']) ?? 0;
        $num = intval($detail_arr[$k]['num']) ?? 0;

        $details[$k]['weight'] = $weight;
        $details[$k]['num'] = $num;
        $details[$k]['other_weight'] = $other_weight;
        $details[$k]['gross_weight'] = $gross_weight;
        $details[$k]['unit_price'] = $unit_price;
        $details[$k]['price'] = $price;
        $details[$k]['level_name'] = $detail_arr[$k]['level_name'];
        $details[$k]['level_code'] = $detail_arr[$k]['level_code'];
        $details[$k]['bill_no'] = $bill_no;
        $details[$k]['created_by'] = $user_name;
        $total_weight += $gross_weight + $other_weight;
        $total_price += $price;
        $total_num += $num;
      }

      $data['total_price'] = $total_price;
      $data['total_weight'] = $total_weight;
      $data['total_num'] =  $total_num;

      $finance['total_weight'] = $total_weight;
      $finance['total_price'] = $total_price;
      $finance['bill_no'] = $bill_no;
      $finance['type'] = 1;
      $finance['create_date'] = $data['create_date'];
      $finance['receiver_code'] = $data['receiver_code'];
      $finance['depart_code'] = $data['depart_code'];

      cmsWareInboundFinance::mk()->save($finance);
      cmsWareInboundDetail::mk()->saveAll($details);
      
    } else {

      $this->cateorys = SystemBase::mk()->items('种类');
      $data['a'] = SystemBase::mk()->items('等级管理');
      $this->levels = json_encode(SystemBase::mk()->items('等级管理'), JSON_UNESCAPED_UNICODE);

      $this->warehouses = CmsWareInfo::mk()->where(['deleted' => 0])
        ->field('ware_code,ware_name')->order('sort', 'asc')->select();

     
      if (isset($data['bill_no'])) {
        $details = cmsWareInboundDetail::mk()->where(['bill_no' => $data['bill_no']])->select();
        $this->details = json_encode($details, JSON_UNESCAPED_UNICODE);
      }
    }
  }

    /**
     * 表单结果处理
     * @param boolean $result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_result(bool $result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('成功！', 'javascript:history.back()');
        }
    }


  /**
   * 入库单详情
   * @auth true
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function detail()
  {
    CmsWareInbound::mForm('detail', 'id');
  }


  protected function _detail_form_filter(array &$data)
  {
    if ($this->request->isPost()) {

      //echo 2342;die;

    } else {
      $this->cateorys = SystemBase::mk()->items('种类');
      $this->warehouses = InboundService::instance()->getWarehouses();
      $this->levels = SystemBase::mk()->items('等级管理');
      if (isset($data['bill_no'])) {
        $this->details = cmsWareInboundDetail::mk()->where(['bill_no' => $data['bill_no']])->select();
      }
    }
  }

 

  /**
   * 编辑入库单
   * @auth true
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function edit()
  {
    CmsWareInbound::mForm('add', 'id');
  }

  protected function _edit_form_filter(array &$data)
  {
    if ($this->request->isPost()) {

      $bill_no = $data['bill_no'];
     
      $user_name = AdminService::instance()->getUserName();
      $data['user_name'] = $user_name;
      $data['user_id'] = AdminService::instance()->getUserId();

      $detail_arr = json_decode($data['details'],true);

      $details = [];
      $total_weight = 0;
      $total_num = 0;
      $total_price = 0;
      foreach ($detail_arr as $k => $value) {

        $weight = floatval($detail_arr[$k]['weight']) ?? 0;
        $other_weight = floatval($detail_arr[$k]['other_weight']) ?? 0;
        $gross_weight = floatval($detail_arr[$k]['gross_weight']) ?? 0;
        $unit_price = floatval($detail_arr[$k]['unit_price']) ?? 0;
        $price = floatval($detail_arr[$k]['price']) ?? 0;
        $num = intval($detail_arr[$k]['num']) ?? 0;

        $details[$k]['weight'] = $weight;
        $details[$k]['num'] = $num;
        $details[$k]['other_weight'] = $other_weight;
        $details[$k]['gross_weight'] = $gross_weight;
        $details[$k]['unit_price'] = $unit_price;
        $details[$k]['price'] = $price;
        $details[$k]['level_name'] = $detail_arr[$k]['level_name'];
        $details[$k]['level_code'] = $detail_arr[$k]['level_code'];
        $details[$k]['bill_no'] = $bill_no;
        $details[$k]['created_by'] = $user_name;
        $total_weight += $gross_weight + $other_weight;
        $total_price += $price;
        $total_num += $num;
      }

      $data['total_price'] = $total_price;
      $data['total_weight'] = $total_weight;
      $data['total_num'] =  $total_num;

      $data['total_price'] = $total_price;

      cmsWareInboundDetail::mk()->where(['bill_no' => $data['bill_no']])->delete();
      cmsWareInboundFinance::mk()->where(['bill_no' => $data['bill_no']])->delete();

      $finance['total_weight'] = $total_weight;
      $finance['total_price'] = $total_price;
      $finance['bill_no'] = $bill_no;
      $finance['type'] = 1;
      $finance['create_date'] = $data['create_date'];
      $finance['receiver_code'] = $data['receiver_code'];
      $finance['depart_code'] = $data['depart_code'];

      cmsWareInboundFinance::mk()->save($finance);

      cmsWareInboundDetail::mk()->saveAll($details);
    } else {

      $this->cateorys = SystemBase::mk()->items('种类');
      $this->levels = SystemBase::mk()->items('等级管理');

      $this->warehouses = InboundService::instance()->getWarehouses();

      if (isset($data['bill_no'])) {
        $details = cmsWareInboundDetail::mk()->where(['bill_no' => $data['bill_no']])->select();
        $this->details = json_encode($details, JSON_UNESCAPED_UNICODE);
      }
    }
  }
}
